//
//  YQDBManager.m
//  EPA--1
//
//  Created by lanou3g on 16/4/28.
//  Copyright © 2016年 刘永庆. All rights reserved.
//

#import "YQDBManager.h"
#import "YTKKeyValueStore.h"
//#import <objc/objc-runtime.h>
#import <objc/runtime.h>
#import <objc/message.h>
@interface YQDBManager ()
@property (nonatomic, strong)YTKKeyValueStore *myStore;
@end
@implementation YQDBManager
static NSString *tableName = @"articl";
//单例
+ (instancetype)shareManager;
{
    
    static YQDBManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [YQDBManager new];
    });
    return manager;
}
- (YTKKeyValueStore *)myStore
{
    if (!_myStore) {
        _myStore = [[YTKKeyValueStore alloc]initDBWithName:@"YQ.sqlite"];
    }
    return _myStore;
}
//收藏
- (void)addArticlModel:(YQHomeListModel *)model
{
    [self.myStore createTableWithName:tableName];
    NSDictionary *dic = [self dictionaryFromModel:model];
    [self.myStore putObject:dic withId:model.ID intoTable:tableName];
    
}
//取消收藏
- (void)cancelArticlWithContentID:(NSString *)contentID
{
    [self.myStore createTableWithName:tableName];
    [self.myStore deleteObjectById:contentID fromTable:tableName];
}
- (BOOL)isAddArticl:(NSString *)contentID
{
    
   NSDictionary *dic =  [self.myStore getObjectById:contentID fromTable:tableName];
    if (dic) {
        return YES;
    }
    return NO;
    
}
- (NSArray *)selectAllArticl
{
    NSArray *items = [self.myStore getAllItemsFromTable:tableName];
    NSMutableArray *array = [NSMutableArray new];
    for (YTKKeyValueItem *item in items) {
        YQHomeListModel *model = [self modelFromDictionary:item.itemObject];
        [array addObject:model];
    }
    return array;
}
- (NSString *)getCollectTimeWith:(NSString *)contentID
{
  YTKKeyValueItem *item = [self.myStore getYTKKeyValueItemById:contentID fromTable:tableName];
    NSDate *date = item.createdTime;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *strDate = [dateFormatter stringFromDate:date];
    return strDate;
}
//相互转化
-(NSDictionary *)dictionaryFromModel:(YQHomeListModel *)model
{
    unsigned int count = 0;
    Ivar *ivarArray = class_copyIvarList([model class], &count);
    NSMutableArray *array = [[NSMutableArray alloc]init];
    for (int i = 0; i < count; i ++) {
        NSString *keys = [NSString stringWithUTF8String:ivar_getName(ivarArray[i])];
        [array addObject:keys];
    }
    return [model dictionaryWithValuesForKeys:array];
}
- (YQHomeListModel *)modelFromDictionary:(NSDictionary *)dic
{
    YQHomeListModel *model = [YQHomeListModel new];
    [model setValuesForKeysWithDictionary:dic];
    return model;
}

@end
